/*
 * Flashlib - QB9 common Flash library
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.qb9.flashlib.display.spritesheet
{
	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.geom.ColorTransform;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	public class SpriteSheetUtil
	{
		private static const ZERO:Point = new Point();
		
		private static function createBitmap(width:Number, height:Number):BitmapData
		{
			return new BitmapData(
				Math.ceil(width),
				Math.ceil(height),
				true, 0
			);
		}

		public static function fromBitmap(source:BitmapData, rects:Array):SpriteSheet
		{
			var frames:Array = [];
			for each (var rect:Rectangle in rects)
			{
				var bd:BitmapData = createBitmap(rect.width, rect.height);
				bd.copyPixels(source, rect, ZERO);
				frames.push(bd);
			}
			
			return new SpriteSheet(frames); 
		}

		public static function fromMovieClip(mc:MovieClip, matrix:Matrix=null, transform:ColorTransform=null):SpriteSheet
		{
			var i:uint = mc.totalFrames;
			var frames:Array = new Array(i);
			
			matrix = matrix || new Matrix();
			
			while (i)
			{
				mc.gotoAndStop(i--);
				
				var bd:BitmapData = createBitmap(
					(mc.width+matrix.tx) * matrix.a, 
					(mc.height+matrix.ty) * matrix.d
				);
				bd.draw(mc, matrix, transform);
				frames[i] = bd;
			}
			
			return new SpriteSheet(frames);
		}
	}
}